package com.jjc.android.view

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.text.format.Formatter
import android.view.View
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.jjc.android.base.BaseActivity
import com.jjc.android.dialog.LoadingDialog
import com.jjc.android.entity.DeviceDto
import com.jjc.android.util.Common.parseEmpty
import com.jjc.android.util.Common.parseTwo
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.FileCallback
import com.lzy.okgo.model.Progress
import com.lzy.okgo.model.Response
import com.lzy.okgo.request.base.Request
import com.yanzhenjie.album.Action
import com.yanzhenjie.album.Album
import com.yanzhenjie.album.AlbumFile
import java.io.File
import java.util.regex.Pattern
import com.hjq.permissions.OnPermissionCallback
import com.hjq.toast.ToastUtils
import com.jjc.android.App
import com.jjc.android.Constants
import com.jjc.android.R
import com.jjc.android.activity.CameraActivity

object CommonKt {
    //isUpToServer true:性别上传至服务器  false：服务器中文性别回显到客户端
    fun String?.genderParse(isUpToServer:Boolean):String{
        if(isNullOrEmpty()) return ""
        return if(isUpToServer){
            if(App.getContext().getString(R.string.man_txt) == this) Constants.Gender_Man
            else Constants.Gender_Woman
        }else{
            if(Constants.Gender_Man == this) App.getContext().getString(R.string.man_txt)
            else App.getContext().getString(R.string.woman_txt)
        }
    }

    fun convertViewToBitmap(view: View): Bitmap {
        view.measure(
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        )
        view.layout(0, 0, view.measuredWidth, view.measuredHeight)
        val bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        val canvas =  Canvas(bitmap)
//        canvas.drawColor(Color.WHITE)
        view.draw(canvas)
        return bitmap
    }

    fun albumPick(context: Context, albumType:Int = Album.FUNCTION_CHOICE_IMAGE, multipleCount: Int = 1, action: Action<List<AlbumFile>>){
        if(XXPermissions.isGranted(context, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)){
            realAlbumPick(context,albumType,multipleCount,action)
        }else{
            XXPermissions.with(context)
                .permission(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                .request(object : OnPermissionCallback{
                    override fun onGranted(
                        permissions: MutableList<String>,
                        allGranted: Boolean
                    ) {
                        realAlbumPick(context,albumType,multipleCount,action)
                    }

                    override fun onDenied(
                        permissions: MutableList<String>,
                        doNotAskAgain: Boolean
                    ) {
                        ToastUtils.show(context.getString(R.string.permission_fail_txt))
                    }
                })
        }

    }

    private fun realAlbumPick(context: Context, albumType:Int, multipleCount: Int = 1, action: Action<List<AlbumFile>>){
        Album.FUNCTION_CHOICE_ALBUM
        if(albumType == Album.FUNCTION_CHOICE_ALBUM){
            Album.album(context).let {
                if(multipleCount>1){
                    it.multipleChoice()
                        .columnCount(3)
                        .selectCount(multipleCount)
                        .camera(true)
                        .onResult{files->
                            action.onAction(files)
                        }
                        .onCancel {

                        }
                        .start()
                }else{
                    it.singleChoice()
                        .columnCount(3)
                        .camera(true)
                        .onResult{files->
                            action.onAction(files)
                        }
                        .onCancel {

                        }
                        .start()
                }
            }
        }else if(albumType == Album.FUNCTION_CAMERA_VIDEO){
            Album.video(context).let {
                if(multipleCount>1){
                    it.multipleChoice()
                        .columnCount(3)
                        .selectCount(multipleCount)
                        .camera(true)
                        .onResult{files->
                            action.onAction(files)
                        }
                        .onCancel {

                        }
                        .start()
                }else{
                    it.singleChoice()
                        .columnCount(3)
                        .camera(true)
                        .onResult{files->
                            action.onAction(files)
                        }
                        .onCancel {

                        }
                        .start()
                }
            }
        }else{
            Album.image(context).let {
                if(multipleCount>1){
                    it.multipleChoice()
                        .columnCount(3)
                        .selectCount(multipleCount)
                        .camera(true)
                        .onResult{files->
                            action.onAction(files)
                        }
                        .onCancel {

                        }
                        .start()
                }else{
                    it.singleChoice()
                        .columnCount(3)
                        .camera(true)
                        .onResult{files->
                            action.onAction(files)
                        }
                        .onCancel {

                        }
                        .start()
                }
            }
        }
    }

    fun downloadFile(context: BaseActivity,fileUrl:String?,showLoading:Boolean=true,errorAction:(String)->Unit,action:(File)->Unit){
        if(XXPermissions.isGranted(context,Permission.MANAGE_EXTERNAL_STORAGE)){
            downloadFile2(context,fileUrl,showLoading,errorAction,action)
        }else{
            XXPermissions.with(context)
                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                .request(object : OnPermissionCallback{
                    override fun onGranted(
                        permissions: MutableList<String>,
                        allGranted: Boolean
                    ) {
                        downloadFile2(context,fileUrl,showLoading,errorAction,action)
                    }

                    override fun onDenied(
                        permissions: MutableList<String>,
                        doNotAskAgain: Boolean
                    ) {
                        errorAction.invoke(App.getContext().getString(R.string.permission_fail_txt))
                    }
                })
        }
    }

    fun downloadFile2(context: BaseActivity,fileUrl:String?,showLoading:Boolean=true,errorAction:(String)->Unit,action:(File)->Unit){
        if(XXPermissions.isGranted(context,Permission.READ_EXTERNAL_STORAGE,Permission.WRITE_EXTERNAL_STORAGE)){
            innerDownloadFile(context,fileUrl,showLoading,errorAction,action)
        }else{
            XXPermissions.with(context)
                .permission(Permission.READ_EXTERNAL_STORAGE,Permission.WRITE_EXTERNAL_STORAGE)
                .request(object : OnPermissionCallback{
                    override fun onGranted(
                        permissions: MutableList<String>,
                        allGranted: Boolean
                    ) {
                        innerDownloadFile(context,fileUrl,showLoading,errorAction,action)
                    }

                    override fun onDenied(
                        permissions: MutableList<String>,
                        doNotAskAgain: Boolean
                    ) {
                        errorAction.invoke(App.getContext().getString(R.string.permission_fail_txt))
                    }
                })
        }
    }

    private fun innerDownloadFile(context: BaseActivity,fileUrl:String?,showLoading:Boolean=true,errorAction:(String)->Unit,action:(File)->Unit){
        if(fileUrl.isNullOrEmpty()) return
        OkGo.get<File>(fileUrl)
            .tag(context)
            .execute(object : FileCallback(){
                private var progressDialog: LoadingDialog? = null
                override fun onStart(request: Request<File, out Request<Any, Request<*, *>>>?) {
                    if(showLoading){
                        progressDialog = LoadingDialog(context,"${context.getString(R.string.down_file_2_txt)}..")
                        progressDialog?.show()
                    }
                }

                override fun onSuccess(response: Response<File>?) {
                    progressDialog?.dismiss()
                    val file = response?.body()
                    if(file!=null){
                        action.invoke(file)
                    }else{
                        errorAction.invoke(context.getString(R.string.down_fail_txt))
                    }

                }

                override fun onError(response: Response<File>?) {
                    progressDialog?.dismiss()
                    errorAction.invoke(context.getString(R.string.down_fail_txt))
                }

                override fun downloadProgress(progress: Progress?) {
                    progress?:return
                    val downloadLength = Formatter.formatFileSize(context, progress.currentSize)
                    val totalLength = Formatter.formatFileSize(context, progress.totalSize)
                    val speed = Formatter.formatFileSize(context, progress.speed)
                    progressDialog?.setMessage(String.format("%s/%s\n%s/s",downloadLength,totalLength,speed))
                }

            })
    }


    @JvmStatic
    fun isPasswordValid(password: String?): Boolean {
        if(password.isNullOrEmpty()) return false
//        if(password.length !in 8..16){
//            return false
//        }
        return true
//        val isContainEn = Pattern.compile(".*[a-zA-z].*").matcher(password).find()
//
//        val isContainNum = Pattern.compile(".*[0-9].*").matcher(password).find()
//        return isContainEn&&isContainNum
//        return password.length in 6..16
    }

    @JvmStatic
    fun isPhoneValid(phone: String?): Boolean {
        return !phone.isNullOrEmpty()&&phone.length==11
    }


    fun getHtmlData(bodyHTML: String?): String {
        val head = ("<head>"
                + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> "
                + "<style>img{max-width: 100%; width:100%; height:auto;}*{margin:0px;}" +
                " body{\n" +
                "     padding: 14px;\n" +
                "word-wrap:break-word;\n" +
                "\n" +
                "font-family:Arial;\n" +
                "\n" +
                "}</style>"
                + "</head>")
        return "<html>$head<body>$bodyHTML</body></html>"
    }
    @JvmStatic
    fun isSmsCodeValid(code: String?): Boolean {
        return !code.isNullOrEmpty()&&code.length==4
    }

    fun List<DeviceDto>?.appendDeviceName(showSuffix:Boolean = true):List<DeviceDto>{
        return if(this==null){
            listOf<DeviceDto>()
        }else if(this.isEmpty()){
            this
        }else{
            this.forEachIndexed { index, deviceDto ->
                deviceDto.deviceName = if(showSuffix){
                    String.format("${App.getContext().getString(R.string.device_txt)}%s(%s)",(index+1).parseTwo(),deviceDto.bhmohipntdlpc61m.parseEmpty().let { if(it.length<=7) it else it.substring(it.length-7)  })
                }else{
                    String.format("${App.getContext().getString(R.string.device_txt)}%s",(index+1).parseTwo())
                }
            }
            this
        }
    }

}